package yjj.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;
import yjj.exception.BusinessException;
import yjj.model.web.PageBean;
import yjj.system.entity.User;
import yjj.system.mapper.UserMapper;
import yjj.system.model.SysUserDTO;
import yjj.system.service.UserDeptService;
import yjj.system.service.UserService;
import yjj.utils.excel.DataProcessor;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserDeptService userDeptService;

    @Override
    public String login(User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        queryWrapper = queryWrapper.eq(User::getUsername, user.getUsername());
        User user1 = this.getOne(queryWrapper);
        if (user1 == null) {
            throw new BusinessException("用户不存在");
        }
        if (!user.getPassword().equals(user1.getPassword())) {
            throw new BusinessException("密码错误");
        }
        return user1.getUserId();
    }

    @Override
    public User findById(String userId) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(User::getUserId, userId);
        User user = this.getOne(queryWrapper);
        return user;
    }

    @Override
    public List<User> listAll() {
        return this.list();
    }

    // 用户唯一项校验
    private void checkUserData(SysUserDTO sysUserDTO) {
        String username = sysUserDTO.getUsername();
        String phoneNumber = sysUserDTO.getPhone();
        String email = sysUserDTO.getEmail();
        String userId = sysUserDTO.getUserId();
        // 查询出与修改后信息冲突的用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(User::getUserId, userId)
                .and(wrapper -> {
                    if (StringUtils.hasText(username)) {
                        wrapper.eq(User::getUsername, username);
                    }
                    if (StringUtils.hasText(email)) {
                        wrapper.or().eq(User::getEmail, email);
                    }
                    if (StringUtils.hasText(phoneNumber)) {
                        wrapper.or().eq(User::getPhone, phoneNumber);
                    }
                });

        // 执行查询
        List<User> conflictingUsers = userMapper.selectList(queryWrapper);
        // 遍历冲突用户，确定具体冲突的字段
        for (User user : conflictingUsers) {
            if (StringUtils.hasText(username) && username.equals(user.getUsername())) {
                throw new BusinessException("用户名已存在");
            }
            if (StringUtils.hasText(phoneNumber) && phoneNumber.equals(user.getPhone())) {
                throw new BusinessException("手机号码已存在");
            }
            if (StringUtils.hasText(email) && email.equals(user.getEmail())) {
                throw new BusinessException("邮箱已存在");
            }
        }
    }

    @Override
    public void update(SysUserDTO sysUserDTO) {
        // 校验用户唯一项
        checkUserData(sysUserDTO);
        // 更新用户信息
        //TODO 密码加密处理
        User user = BeanUtil.copyProperties(sysUserDTO, User.class);
        this.updateById(user);
        //当前登录用户与修改用户SysUserDTO可能不是同一个人
        // ，也不确定userId有没有值

        // 保存用户部门
        saveUserDept(sysUserDTO.getUserId(), sysUserDTO.getDeptIdList());

    }

    @Override
    public void process(List<User> userList) {
        // 这里可以添加数据验证逻辑
        // 例如，检查必填字段是否为空，数据格式是否正确等
        for (User user : userList) {

            if (user.getUsername() == null || user.getUsername().trim().isEmpty()) {
                throw new RuntimeException("用户名不能为空");
            }
            if (user.getEmail() == null || !user.getEmail().matches("^[\\w.-]+@[\\w.-]+\\.\\w+$")) {
                throw new RuntimeException("邮箱格式不正确");
            }
        }
        // 保存数据到数据库
        this.saveBatch(userList);
    }


    private void saveUserDept(String userId, List<String> deptIdList) {

    }

    @Override
    public PageBean<User> pagelist(int pageNum, int pageSize) {
        Page<User> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(User::getDelFlag, "1");// 查询未删除的用户
        //Page 是 IPage 的具体实现类
        Page<User> userIPage = userMapper.selectPage(page, queryWrapper);
        PageBean<User> pageBean = new PageBean<>(userIPage);
        return pageBean;
    }

    @Override
    public PageBean<User> search(Map map) {
        Integer pageNum = (Integer) map.get("pageNum");
        Integer pageSize = (Integer) map.get("pageSize");

        // 获取嵌套的 search Map
        Map<String, Object> searchMap = (Map<String, Object>) map.get("search");
        //{pageNum=1, pageSize=10, search={username=, phone=, status=1, createTimeList=[2024-10-27T16:00:00.000Z, 2024-11-03T16:00:00.000Z], deptIdList=[1842128938393600002, 1842128590274756609]}}

        // 从 search Map 中获取值
        String username = (String) searchMap.get("username");
        String phone = (String) searchMap.get("phone");
        String status = (String) searchMap.get("status");
        List<String> createTimeList = (List<String>) searchMap.get("createTimeList");
        List<String> deptIdList = (List<String>) searchMap.get("deptIdList");

        System.out.println("deptIdList:"+deptIdList);
        System.out.println("createTimeList:"+createTimeList);
        //把日期字符串转换为日期对象
        LocalDateTime startTime = null;
        LocalDateTime endTime = null;
        if (createTimeList != null && createTimeList.size() == 2) {
            //OffsetDateTime适用于解析带有 "Z" 的日期字符串。
            startTime = OffsetDateTime.parse(createTimeList.get(0), DateTimeFormatter.ISO_OFFSET_DATE_TIME).toLocalDateTime();
            endTime = OffsetDateTime.parse(createTimeList.get(1), DateTimeFormatter.ISO_OFFSET_DATE_TIME).toLocalDateTime();
        }
        List<String> departs = null;
        if(!deptIdList.isEmpty()){
            departs = userDeptService.findDeparts(deptIdList);
            if (departs == null|| departs.isEmpty()) {
                return new PageBean<>();
            }
        }
        System.out.println("departs:"+departs);
        Page<User> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(username), User::getUsername, username)
                .like(StringUtils.hasText(phone), User::getPhone, phone)
                .eq(StringUtils.hasText(status), User::getStatus, status)
                .between(createTimeList != null && createTimeList.size() == 2, User::getCreateTime, startTime, endTime)
                .in(departs!=null,User::getUserId, departs);

        Page<User> userIPage = userMapper.selectPage(page, queryWrapper);
        return new PageBean<>(userIPage);
    }

}
